package com.opensource.component.api;

import com.opensource.component.register.RegisterInterfaceStatement;
import com.opensource.component.register.RegisterStatementManager;
import com.opensource.component.register.RegisterStatementRpcClient;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * 放在服务端API中
 *
 * @author ZonLen since on 2022/5/31 上午9:48
 */
@Component
public class DeclareReportClientRegister implements ApplicationRunner {

  private final RegisterStatementRpcClient registerStatementRpcClient;

  public DeclareReportClientRegister(
      RegisterStatementRpcClient registerStatementRpcClient) {
    this.registerStatementRpcClient = registerStatementRpcClient;
  }

  @Override
  public void run(ApplicationArguments args) throws Exception {
    final Map<String, RegisterInterfaceStatement> clientRegisterInterfaceStatement = RegisterStatementManager
        .clientRegisterInterfaceStatement();
    if (clientRegisterInterfaceStatement.isEmpty()) {
      return;
    }
    Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(() -> {
      //注册到服务端
      registerStatementRpcClient
          .registerInterfaceStatements(new ArrayList<>(clientRegisterInterfaceStatement.values()));
    }, 30, 30, TimeUnit.SECONDS);
  }
}
